import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import {ElMessage} from 'element-plus'
import {staticRoutes} from '@/router/routes'
import { getUserInfoApi, loginApi, logoutApi } from '@/api/acl/login';


/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

	state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: []
  }),

	actions: {
    // 登陆的异步action
    async login (username: string, password: string) {
      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     if (username==='admin' && password==='111111') {
      //       const token = 'token-atguigu'
      //       setToken(token)
      //       this.token = token
      //       resolve(token)
      //     } else {
      //       reject(new Error('用户名或密码错误!'))
      //       ElMessage.error('用户名或密码错误!')
      //     }
      //   }, 1000)
      // })

      // 发送登陆的请求
      const result = await loginApi(username, password)
      // 请求成功后, 取出token保存  pinia和local中
      const token = result.token
      this.token = token
      setToken(token)
    },

    async getInfo () {
      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     this.name = 'admin'
      //     this.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
      //     this.menuRoutes = staticRoutes
      //     resolve({name: this.name, avatar: this.avatar, token: this.token})
      //   }, 1000)
      // })

      // 请求获取用户信息
      const result = await getUserInfoApi()
      // 请求成功后, 读取用户信息name和avatar, 保存到state
      const {name, avatar} = result
      this.name = name
      this.avatar = avatar
      // 将静态路由表保存到state
      this.menuRoutes = staticRoutes

    },

    async reset () {

      // 如果当前有用户名, 请求退出登陆接口
      if (this.name) {
        await logoutApi() // 加await后, 下面的代码是在请求成功后执行的
      }

      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.name = ''
      this.avatar = ''
    },
	},
});
